import React, { Component } from 'react';
import {Image, StyleSheet, Text, View, TextInput, ScrollView, TouchableOpacity, DeviceEventEmitter} from 'react-native';
import Confirm from '../../../components/confirm/Confirm'
import ReactNativePickerSelect from 'react-native-picker-select'
import Toast from 'react-native-easy-toast'
import Loading from '../../../components/loading/index'
import { API } from "../../../api";
import { i18n } from "../../../utils/locales/i18n";

type Props = {};
export default class AdvertiseModify extends Component<Props> {
    static navigationOptions = ({ navigation }) => {
        return {
            title: i18n.t('i159'),
            headerTintColor: '#0f0f0f',
            headerBackTitle: null
        }
    }
    constructor() {
        super()
        this.state = {
            ad_price: '',
            modalVisible: false,
            defeatModalVisible: false,
            loading: false,
            currentToastInfo: '',
            // 广告类型
            adType: '0',
            // 交易银行卡号
            txBankNum: '',

            min: '',
            max: '',
            unit: '',

            // 初始化数据
            // 手续费
            fee: '',
            // 限额
            adLimit: '',
            // 银行卡列表
            bankList: '',
            // 市场极限价
            marketPrice: '',
            // 广告id
            adId: ''
        }
    }
    componentDidMount(): void {
        const item = this.props.navigation.getParam('item')
        // AdUsername: "dewdew"
        // BankName: "4321234"
        // BankNumber: "6222600260001072444"
        // BuyToken: "hkd"
        // Created: 1546481599
        // FeeFreeze: 0.005
        // FeeRate: 0.005
        // Freeze: 1
        // Id: 44
        // Max: 43
        // Min: 43
        // SellToken: "fcc"
        // State: 2
        // Type: 2
        // Uid: 17
        // Unit: 43
        // Updated: 0
        // key: "44"
        // type: 2
        this.setState({
            adId: item.Id,
            adType: item.BuyToken === 'fcc' ? '0' : '1',
            min: item.Min + '',
            max: item.Max + '',
            unit: item.Unit + '',
        }, () => {
            this._initData()
        })
    }

    _initData = async () => {
        this.setState({
            loading: true
        })
        const [adFeeRes, adLimitRes, bankListRes, marketPriceRes] = await Promise.all([
            API._fetch('getAdFee', {}, 'GET'),
            API._fetch('getAdLimit', { token: this.state.adType === '0' ? "fcc" : 'hkd' }),
            API._fetch('getBank', {}, 'GET'),
            API._fetch('getMarketPrice', {
                "type": this.state.adType === '0' ? 1 : 2,
                "sellToken": this.state.adType === '0' ? "hkd" : 'fcc',
                "buyToken": this.state.adType === '0' ? "fcc" : 'hkd'
            })
        ])
        if (bankListRes.data.length > 0) {
            bankListRes.data.forEach(item => {
                item.label = item.Number
                item.value = item.Id
            })
        } else {
            this.setState({
                modalVisible: false
            })
        }
        this.setState({
            fee: Number(adFeeRes.data) * 100,
            adLimit: adLimitRes.data,
            bankList: bankListRes.data,
            marketPrice: marketPriceRes.data.Price
        })
        this.setState({
            loading: false
        })
        // 0:
        // code: 10000
        // data: 0.005
        // msg: "获取信息成功"
        // status: 200
        // __proto__: Object
        // 1:
        // code: 10000
        // data:
        //     Max: 10000
        // Min: 10
        // __proto__: Object
        // msg: "获取信息成功"
        // status: 200
        // __proto__: Object
        // 2:
        // code: 10000
        // data: [
            // 0:
            // Id: 34
            // Name: "Niudiedie"
            // Number: "6221888200604489572"
            // Uid: 0
        // ]
        // msg: "获取信息成功"
        // status: 200
        // __proto__: Object
        // 3:
        // code: 10000
        // data:
        //     Price: 2
        // __proto__: Object
        // msg: "获取信息成功"
        // status: 200

    }
    // 执行修改广告
    publishAd = async () => {
        // 购买参数
            // bankId: 34
            // buyToken: "fcc"
            // max: "344"
            // min: "32"
            // sellToken: "hkd"
            // type: 1
            // unit: "21"
        // 出售参数
            // bankId: 34
            // buyToken: "hkd"
            // max: "234"
            // min: "43"
            // sellToken: "fcc"
            // type: 2
            // unit: "43"
        if (!this.state.txBankNum ) {
            this.refs.toast.show(i18n.t('i83'))
            return
        }
        if (!this.state.max || !this.state.min || !this.state.unit) {
            this.refs.toast.show(i18n.t('plz_cpl'))
            return
        }
        if (Number(this.state.min) > Number(this.state.max)) {
            this.refs.toast.show(i18n.t('i160'))
            return
        }
        if (Number(this.state.min) < Number(this.state.adLimit.Min) || Number(this.state.max) > Number(this.state.adLimit.Max)) {
            this.refs.toast.show(i18n.t('overflow'))
            return
        }
        const reqData = {
            "id": this.state.adId,
            "unit": this.state.unit,
            "max": this.state.max,
            "min": this.state.min,
            "bankId": this.state.txBankNum,
        }
        if (!this.state.bankList) {
            this.setState({
                modalVisible: true
            })
        }
        this.setState({
            loading: true
        })
        const res = await API._fetch('modifyAd', reqData)
        this.setState({
            loading: false,
            modalVisible: true
        })
        if (res.code === 10000) {
            this.refs.toast.show(res.msg || i18n.t('o_success'))
            setTimeout(() => {
                DeviceEventEmitter.emit('refresh_ad');
                this.props.navigation.goBack()
            }, 1000)
        } else {
            this.refs.toast.show(res.msg || i18n.t('o_defeat'))
        }
    }


    // 确认发布广告
    handleCancel = () => {
        this.setState({
            modalVisible: false
        })
    }
    handleConfirm = () => {
        this.setState({
            modalVisible: false,
            // defeatModalVisible: true
        })
        this.publishAd()
    }
    // 发布广告失败处理
    handleIKnow = () => {
        this.setState({
            defeatModalVisible: false
        })
    }
    render() {
        return (
            <View style={{ flex: 1 }}>
                {/*toast*/}
                <Toast ref="toast" position='bottom' positionValue={200}/>
                { this.state.loading ? (
                    <Loading
                        info={this.state.currentToastInfo}
                    />) : null }
                <View style={[styles.container, { borderBottomWidth: 10, borderBottomColor: '#f2f2f2' }]}>
                    <View style={{ paddingVertical: 15 }}>
                        <View>
                            <Text style={{ fontSize: 13, lineHeight: 22, color: '#808080' }}>{i18n.t('i161')}<Text style={{ color: '#2c61f8' }}>{i18n.t('i162')}</Text>{i18n.t('i163')}</Text>
                        </View>
                        <View>
                            <Text style={{ fontSize: 13, lineHeight: 22, color: '#808080' }}>{ i18n.t('i164') }{ this.state.fee }%。 </Text>
                        </View>
                        <View>
                            <Text style={{ fontSize: 13, lineHeight: 22, color: '#808080' }}>{i18n.t('i165')}</Text>
                        </View>
                    </View>
                    {/*select item wrapper*/}
                    <View>
                        {/*select item*/}
                        <View style={{ height: 50, width: '100%', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', borderTopColor: '#eee', borderTopWidth: 0.5 }}>
                            <View style={{ justifyContent: 'center', alignItems: 'center' }}>
                                <Text style={{ color: '#0f0f0f', fontSize: 16 }}>{i18n.t('i166')}</Text>
                            </View>
                            <TouchableOpacity style={{ flex: 1, height: '100%', justifyContent: 'center' }}>
                                <View style={{ width: '100%', flexDirection: 'row', justifyContent: 'flex-end' }}>
                                    <View style={{ flexDirection: 'row', alignItems: 'center', position: 'relative' }}>
                                        <Text style={{ color: '#808080', fontSize: 13 }}>{ this.state.adType == '0' ? i18n.t('i167') : i18n.t('i168') }</Text>
                                        {/*<ReactNativePickerSelect*/}
                                            {/*style={{...pickerSelectStyles}}*/}
                                            {/*items={[*/}
                                                {/*{ label: '购买广告', value: '0' },*/}
                                                {/*{ label: '出售广告', value: '1' }*/}
                                            {/*]}*/}
                                            {/*value={this.state.adType}*/}
                                            {/*hideIcon={true}*/}
                                            {/*// onValueChange={(adType) => {this.setState({adType})}}*/}
                                            {/*onValueChange={(adType) => this.changeAdType(adType)}*/}
                                        {/*/>*/}
                                        {/*<Image resizeMode={'contain'} style={{width: 10, height: 10, position: 'absolute', top: '40%', right: 5}} source={require('@images/mine/icon_triangle.png')}/>*/}
                                        {/*<Image style={{width: 10, height: 10}} source={require('../../../images/adver/arrow.png')}/>*/}
                                    </View>
                                </View>
                            </TouchableOpacity>
                        </View>
                        <View style={{ height: 60, width: '100%', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', borderTopColor: '#eee', borderTopWidth: 0.5 }}>
                            <View style={{ justifyContent: 'center', alignItems: 'center' }}>
                                { this.state.adType === '0' ? (
                                    <Text style={{ color: '#0f0f0f', fontSize: 16 }}>{i18n.t('i169')}</Text>
                                ) : (
                                    <Text style={{ color: '#0f0f0f', fontSize: 16 }}>{i18n.t('i169')}</Text>
                                ) }
                            </View>
                            <TouchableOpacity style={{ flex: 1, height: '100%', justifyContent: 'center' }}>
                                <View style={{ width: '100%', flexDirection: 'row', justifyContent: 'flex-end', paddingRight: 10 }}>
                                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                        <Text style={{ color: '#808080' }}>FCC</Text>
                                        {/*<Image style={{width: 10, height: 10}} source={require('../../../images/adver/arrow.png')}/>*/}
                                    </View>
                                </View>
                            </TouchableOpacity>
                        </View>
                        <View style={{ height: 60, width: '100%', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', borderTopColor: '#eee', borderTopWidth: 0.5 }}>
                            <View style={{ justifyContent: 'center', alignItems: 'center' }}>
                                <Text style={{ color: '#0f0f0f', fontSize: 16 }}>{i18n.t('i171')}</Text>
                            </View>
                            <TouchableOpacity style={{ flex: 1, height: '100%', justifyContent: 'center' }}>
                                <View style={{ width: '100%', flexDirection: 'row', justifyContent: 'flex-end', paddingRight: 10 }}>
                                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                        <Text style={{ color: '#808080' }}>HKD</Text>
                                        {/*<Image style={{width: 10, height: 10}} source={require('../../../images/adver/arrow.png')}/>*/}
                                    </View>

                                </View>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
                <ScrollView style={[styles.container, { flex: 1}]}>
                    <View style={{ width: '100%' }}>
                        {/*list item*/}
                        <View style={[styles.container, { borderBottomWidth: 0.5, borderBottomColor: '#eee', flexDirection: 'row', alignItems: 'center', height: 50 }]}>
                            <View style={{ width: '30%' }}><Text>{ i18n.t('i172') }</Text></View>
                            <View style={{ flex: 1 }}>
                                <TextInput
                                    style={{height: '100%', width: '100%', borderLeftWidth: 0.5, borderLeftColor: '#eee', paddingLeft: 20}}
                                    onChangeText={(unit) => this.setState({unit})}
                                    placeholder={i18n.t('i236')}
                                    value={this.state.unit}
                                    keyboardType={'numeric'}
                                />
                            </View>
                            <View>
                                <Text style={{color: '#808080'}}>HKD</Text>
                            </View>
                        </View>
                        {/*/!*售价提示*!/*/}
                        <View style={[styles.container, { height: 40, justifyContent: 'center', borderBottomColor: '#eee', borderBottomWidth: 0.5 }]}>
                            <Text style={{ color: '#ff7606' }}>{i18n.t('i238')}：<Text>{ this.state.marketPrice }</Text></Text>
                        </View>
                        {/*{ this.state.adType === '0' ? (*/}
                            {/*<View style={[styles.container, { height: 40, justifyContent: 'center', borderBottomColor: '#eee', borderBottomWidth: 0.5 }]}>*/}
                                {/*<Text style={{ color: '#ff7606' }}>{i18n.t('i173')}：<Text>{ this.state.marketPrice }</Text></Text>*/}
                            {/*</View>*/}
                        {/*) : (*/}
                            {/*<View style={[styles.container, { height: 40, justifyContent: 'center', borderBottomColor: '#eee', borderBottomWidth: 0.5 }]}>*/}
                                {/*<Text style={{ color: '#ff7606' }}>{i18n.t('i174')}：<Text>{ this.state.marketPrice }</Text></Text>*/}
                            {/*</View>*/}
                        {/*) }*/}
                        {/*交易限制设置*/}
                        <View style={[styles.container, { width: '100%', height: 60, flexDirection: 'row', alignItems: 'center' }]}>
                            <Image source={require('../../../images/adver/icon-setting.png')} style={{ width: 20, height: 20, marginRight: 10 }}/>
                            <Text style={{ fontSize: 16 }}>{i18n.t('i175')}</Text>
                        </View>
                        <View style={{ height: 60, width: '100%', flexDirection: 'row', borderBottomWidth: 0.5, borderBottomColor: '#eee', justifyContent: 'space-between', alignItems: 'center', borderTopColor: '#eee', borderTopWidth: 1 }}>
                            <View style={{ justifyContent: 'center', alignItems: 'center' }}>
                                <Text style={{ color: '#0f0f0f', fontSize: 16 }}>{i18n.t('i176')}</Text>
                            </View>
                            <TouchableOpacity style={{ flex: 1, height: '100%', justifyContent: 'center' }}>
                                <View style={{ width: '100%', flexDirection: 'row', justifyContent: 'flex-end' }}>
                                    <View style={{ flexDirection: 'row', alignItems: 'center', position: 'relative' }}>
                                        {this.state.bankList ? (
                                            <ReactNativePickerSelect
                                                style={{...pickerSelectStyles}}
                                                items={this.state.bankList}
                                                value={this.state.txBankNum}
                                                hideIcon={true}
                                                placeholder={{
                                                    label: i18n.t('i95'),
                                                    value: null,
                                                    color: '#9EA0A4',
                                                }}
                                                onValueChange={(txBankNum) => {this.setState({txBankNum})}}
                                            />
                                        ) : null}
                                        <Image resizeMode={'contain'} style={{width: 10, height: 10, position: 'absolute', top: '40%', right: 5}} source={require('@images/mine/icon_triangle.png')}/>
                                        {/*<Image style={{width: 10, height: 10}} source={require('../../../images/adver/arrow.png')}/>*/}
                                    </View>
                                </View>
                            </TouchableOpacity>
                        </View>
                        {/*最小限额*/}
                        <View style={[styles.container, { borderBottomWidth: 0.5, borderBottomColor: '#eee', flexDirection: 'row', alignItems: 'center', height: 50 }]}>
                            <View style={{ width: '30%' }}><Text>{i18n.t('i177')}</Text></View>
                            <View style={{ flex: 1 }}>
                                <TextInput
                                    style={{height: '100%', width: '100%', borderLeftWidth: 0.5, borderLeftColor: '#eee', paddingLeft: 20}}
                                    onChangeText={(min) => this.setState({min})}
                                    // placeholder={'输入最小限额'}
                                    keyboardType={'numeric'}
                                    value={this.state.min}
                                />
                            </View>
                            { this.state.adType === '0' ? (
                                <View>
                                    <Text style={{color: '#808080'}}>FCC</Text>
                                </View>
                            ) : (
                                <View>
                                    <Text style={{color: '#808080'}}>HKD</Text>
                                </View>
                            ) }
                        </View>
                        <View style={[styles.container, { height: 40, justifyContent: 'center', borderBottomColor: '#eee', borderBottomWidth: 0.5 }]}>
                            <Text style={{ color: '#ff7606' }}>{i18n.t('i178')}:
                                <Text>{ this.state.adLimit ? this.state.adLimit.Min : '---' }</Text>
                            </Text>
                        </View>
                        {/*最大限额*/}
                        <View style={[styles.container, { borderBottomWidth: 0.5, borderBottomColor: '#eee', flexDirection: 'row', alignItems: 'center', height: 50 }]}>
                            <View style={{ width: '30%' }}><Text>{i18n.t('i179')}</Text></View>
                            <View style={{ flex: 1 }}>
                                <TextInput
                                    style={{height: '100%', width: '100%', borderLeftWidth: 0.5, borderLeftColor: '#eee', paddingLeft: 20}}
                                    onChangeText={(max) => this.setState({max})}
                                    // placeholder={'输入最大限额'}
                                    keyboardType={'numeric'}
                                    value={this.state.max}
                                />
                            </View>
                            { this.state.adType === '0' ? (
                                <View>
                                    <Text style={{color: '#808080'}}>FCC</Text>
                                </View>
                            ) : (
                                <View>
                                    <Text style={{color: '#808080'}}>HKD</Text>
                                </View>
                            ) }
                        </View>
                        <View style={[styles.container, { height: 40, justifyContent: 'center', borderBottomColor: '#eee', borderBottomWidth: 0.5 }]}>
                            <Text style={{ color: '#ff7606' }}>{i18n.t('i180')}:
                                <Text>{ this.state.adLimit ? this.state.adLimit.Max : '---' }</Text>
                            </Text>
                        </View>
                    </View>
                </ScrollView>
                {/*发布广告按钮*/}
                <TouchableOpacity onPress={ () => this.publishAd() } style={{ height: 50 }}>
                    <View style={{ flex: 1, backgroundColor: '#ff7606', justifyContent: 'center', alignItems: 'center' }}>
                        <Text style={{ color: '#fff', fontSize: 16 }}>{i18n.t('i181')}</Text>
                    </View>
                </TouchableOpacity>
                {/*发布广告弹框确认*/}
                <Confirm
                    title={i18n.t('info')}
                    negative={i18n.t('cancel')}
                    positive={i18n.t('confirm')}
                    modalVisible={this.state.modalVisible}
                    handleCancelOrder={this.handleIKnow}
                    handleConfirmOrder={this.handleConfirm}
                >
                    <View style={{flex: 1, paddingVertical: 10}}>

                        <View style={{flex: 1, paddingVertical: 10, justifyContent: 'center', alignItems: 'center'}}>
                            <Text style={{ fontSize: 16, color: '#808080' }}>{i18n.t('i182')}</Text>
                            <Text style={{ fontSize: 16, color: '#808080' }}>{i18n.t('i183')}</Text>
                        </View>
                        {/*<View style={{flex: 1, flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center'}}>*/}
                            {/*<Text style={{flex: 1, textAlign: 'center'}}>购买价格</Text>*/}
                            {/*<Text style={{flex: 1, textAlign: 'center'}}>6 CNY</Text>*/}
                        {/*</View>*/}
                        {/*<View style={{flex: 1, flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center'}}>*/}
                            {/*<Text style={{flex: 1, textAlign: 'center'}}>收购数量</Text>*/}
                            {/*<Text style={{flex: 1, textAlign: 'center'}}>1000 FCC</Text>*/}
                        {/*</View>*/}
                        {/*<View style={{flex: 1, flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center'}}>*/}
                            {/*<Text style={{flex: 1, textAlign: 'center'}}>交易限额</Text>*/}
                            {/*<Text style={{flex: 1, textAlign: 'center'}}>{this.state.min} - { this.state.max } { this.state.adType === '0' ? 'FCC' : 'HKD' }</Text>*/}
                        {/*</View>*/}
                    </View>
                </Confirm>
                {/*发布广告失败*/}
                {/*<Confirm*/}
                    {/*title={'提示'}*/}
                    {/*negative={'我知道了'}*/}
                    {/*isSingleButton={true}*/}
                    {/*modalVisible={true}*/}
                    {/*handleCancelOrder={this.handleIKnow}*/}
                {/*>*/}
                    {/*<View style={{flex: 1, paddingVertical: 10, justifyContent: 'center', alignItems: 'center'}}>*/}
                        {/*<Text style={{ fontSize: 16, color: '#808080' }}>未进行实名认证/未绑定银行卡</Text>*/}
                        {/*<Text style={{ fontSize: 16, color: '#808080' }}>请前往【我的】页面进行认证</Text>*/}
                    {/*</View>*/}
                {/*</Confirm>*/}
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        paddingHorizontal: 10
    }
});

const pickerSelectStyles = StyleSheet.create({
    inputIOS: {
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 40,
        paddingHorizontal: 10,
        borderWidth: 0,
        borderColor: '#d2d2d2',
        borderRadius: 5,
        borderBottomLeftRadius: 0,
        borderTopLeftRadius: 0,
        backgroundColor: 'white',
        color: '#808080',
        marginVertical: 5,
        paddingRight: 25
    },
    inputAndroid: {
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 40,
        paddingHorizontal: 10,
        borderWidth: 0,
        borderColor: '#d2d2d2',
        borderRadius: 5,
        borderBottomLeftRadius: 0,
        borderTopLeftRadius: 0,
        backgroundColor: 'white',
        color: '#808080',
        marginVertical: 5,
        paddingRight: 25
    },
});
